package com.shadow.demo.shiro.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shadow.demo.common.bo.R;
import com.shadow.demo.data.BaseController;
import com.shadow.demo.data.shiro.entity.User;
import com.shadow.demo.shiro.service.UserRoleService;
import com.shadow.demo.shiro.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    private final UserService userService;
    private final UserRoleService userRoleService;

    UserController(UserService userService, UserRoleService userRoleService) {
        this.userService = userService;
        this.userRoleService = userRoleService;
    }

    @PostMapping("/list")
    public R getUserList(@RequestParam Map<String, Object> params) {
        Page<User> page = userService.getList(params);
        return successPage(page);
    }

    @GetMapping("detail/{id}")
    public R detail(@PathVariable String id) {
        return R.success(userService.getById(id));
    }

    @PostMapping("save")
    public R save(@RequestBody User user) {
        String msg = saveVerify(user);
        if (msg != null) {
            return R.fail(msg);
        }
        if (userService.verifyExist(user.getAccount())) {
            return R.fail("账号已经存在");
        }
        LocalDateTime now = LocalDateTime.now();
        user.setCreateTime(now)
                .setModifyTime(now);
        return R.success(userService.save(user));
    }

    @PostMapping("update")
    public R update(@RequestBody User user) {
        String msg = saveVerify(user);
        if (msg != null) {
            return R.fail(msg);
        }
        if (!userService.verifyEditable(user.getId())) {
            return R.fail("账号不可被编辑");
        }
        user.setModifyTime(LocalDateTime.now());
        return R.success(userService.saveOrUpdate(user));
    }

    @PostMapping("config/role/{id}")
    public R configRole(
            @PathVariable("id") String id,
            @RequestBody List<String> roleList
    ) {
        return R.success(userRoleService.configRole(id, roleList));
    }

    @PostMapping("/del/{ids}")
    public R del(@PathVariable("ids") String ids) {
        int change = userService.delete(ids);
        return R.success(change);
    }

    /**
     * 保存验证
     * @return 通过 null
     *         不通过 msg
     * */
    private String saveVerify(final User user) {
        if (StringUtils.isBlank(user.getName())) {
            return "姓名不能为空";
        }
        if (StringUtils.isBlank(user.getAccount())) {
            return "账号不能为空";
        }
        if (StringUtils.isBlank(user.getPassword())) {
            return "密码不能为空";
        }
        return null;
    }
}
